#run.py
#!/usr/bin/python3

import aliLink,mqttd
import time,json
import AgriculturalAutomaticMonitoringSystem as AAMS
import rpi


# 三元素（iot后台获取）
ProductKey = 'h7k4KGmNF55'
DeviceName = 'raspberry1'
DeviceSecret = "ef16185d94045adb8182b609fdbfe9f0"
# topic (iot后台获取)
POST = '/sys/h7k4KGmNF55/raspberry1/thing/event/property/post'  # 上报消息到云
POST_REPLY = '/sys/h7k4KGmNF55/raspberry1/thing/event/property/post_reply'  
SET = '/sys/h7k4KGmNF55/raspberry1/thing/service/property/set'  # 订阅云端指令


# 消息回调（云端下发消息的回调函数）
def on_message(client, userdata, msg):
    #print(msg.payload)
    Msg = json.loads(msg.payload)
    switch = Msg['params']['PowerLed']
    rpi.powerLed(switch)
    print(msg.payload)  # 开关值

#连接回调（与阿里云建立链接后的回调函数）
def on_connect(client, userdata, flags, rc):
    pass



# 链接信息
Server,ClientId,userNmae,Password = aliLink.linkiot(DeviceName,ProductKey,DeviceSecret)

# mqtt链接
mqtt = mqttd.MQTT(Server,ClientId,userNmae,Password)
mqtt.subscribe(SET) # 订阅服务器下发消息topic
mqtt.begin(on_message,on_connect)


# 信息获取上报，每2秒钟上报一次系统参数
AAMS.makerobo_setup()
while True:
    time.sleep(2)
    data_device = AAMS.makerobo_main()
    Lightvalue = data_device[2]
    Rainvalue = data_device[3]
    CurrentTemperature = data_device[1]
    RelativeHumidity = data_device[0]

    # 构建与云端模型一致的消息结构
    updateMsn = {
        'Lightvalue':Lightvalue,
        'Rainvalue':Rainvalue,
        'CurrentTemperature':CurrentTemperature,
        'RelativeHumidity':RelativeHumidity,
    }
    JsonUpdataMsn = aliLink.Alink(updateMsn)
    print(JsonUpdataMsn)

    mqtt.push(POST,JsonUpdataMsn) # 定时向阿里云IOT推送我们构建好的Alink协议数据
